package com.musollo.mp3tools;

import org.apache.log4j.Logger;

import com.musollo.domain.MP3;
import com.musollo.exceptions.CriteriaException;
import com.musollo.exceptions.UpdateException;

public abstract class AbstractMP3Updater implements MP3Updater {

	private static final Logger LOGGER = Logger.getLogger(AbstractMP3Updater.class);
	public static final int LENGTH_OFFSET_FACTOR = 2;
	protected MP3 mp3ToUpdate;

	private void updateMP3() throws UpdateException {
		UpdateCriteria updateCriteria = new UpdateCriteria();
		boolean trackUpdated = updateTrack(updateCriteria);

		while (!trackUpdated) {
			try {
				updateCriteria.removeLowestCriteria();

				trackUpdated = updateTrack(updateCriteria);
			} catch (CriteriaException e) {
				throw new UpdateException();
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void updateMP3(final MP3 mp3) {
		this.mp3ToUpdate = mp3;

		try {
			this.updateMP3();
		} catch (UpdateException e) {
			LOGGER.warn("Could not update MP3, not enough data" + mp3.getMp3File().getAbsolutePath());
		}
	}

	protected abstract boolean updateTrack(UpdateCriteria updateCriteria);
}
